package org.tvolkov.mycompany

class CompanyService {

    def getCompanyList(params) {
		return Company.list().collect{[
			text : it.name,
			id   : ("company" + it.id)
		]};
    }
	
	def addNewCompany(params){
		println("CompanyService: add: params: " + params);
		def newCompany = new Company();
		newCompany.name = params["name"];
		newCompany.address = params["address"];
		newCompany.phoneNumber = params["phone"];
		if (newCompany.save() != null){
			return ["success": "true"];
		} else {
			return ["success": "false"];
		}
	}
	
	def removeCompany(params){
		Company.get(params["nodeid"]).delete();
		
		return ["success": "true"];
	}
	
	def getCompanyDetails(params){
		def company = Company.get(params["nodeid"]);
		return [text:company.name,
				id: ("company" + company.id),
				address: company.address,
				phone: company.phoneNumber];
	}
	
	def editCompany(params){
		println("CompanyService: edit: params: " + params);
		def company = Company.get(params["nodeid"]);
		println("CompanyService: edit: company: " + company);
		if (params["name"]){
			if (company.name != params["name"]){
				company.name = params["name"];
				println("CompanyService: set name " + params["name"]);
			} else {
				println("CompanyService: set name fail");
			}
		}
		if (params["address"]){
			if (company.address != params["address"]){
				company.address = params["address"];
				println("CompanyService: set address " + params["address"]);
			} else {
				println("CompanyService: set address fail");
			}
		}
		if (params["phone"]){
			if (company.phoneNumber != params["phone"]){
				company.phoneNumber = params["phone"];
				println("CompanyService: set phone " + params["phone"]);
			} else {
				println("CompanyService: set phone fail");
			}
		}
		
		if (company.save()){
			println("CompanyService: save ok");
			return ["success": "true"];
		} else {
			println("CompanyService: save fail");
			return ["success": "false"];
		}
	}
}
